import React, {useEffect, useState} from 'react'
import {Button, Form, Input, Table, Card, message, Tooltip} from 'antd';
import style from "./index.module.css"
import {SearchOutlined, EditOutlined, DeleteOutlined} from '@ant-design/icons';
import {
  getHospitalSetListRequest,
  deleteHosRequest,
  batchDeleteRequest
} from "@api//hospital/hospitalSet"
import type {
  getHosSetListRecordsType,
  getHosSetListItem,
  key
} from "@api/hospital/model/hospitalSetTypes"
import {useNavigate} from "react-router-dom";


interface fieldsValueType {
  hosname?: string,
  hoscode?: string
}


export default function HospitalSet() {

  const navigate = useNavigate()
  //创建列表基础数据
  const [tableData, setTableData] = useState<getHosSetListRecordsType>([])
  //设置当前页码
  const [current, setCurrent] = useState(1)
  //设置一页多少个
  const [pageSize, setPageSize] = useState(4)
  //设置医院总数
  const [total, setTotal] = useState(0)
  //设置是否加载
  const [isLoading, setIsLoading] = useState(false)
  //设置查询返回值
  const [fieldsValue, setFieldsValue] = useState<fieldsValueType>({})
  //添加页面重新渲染
  const [reRender, setReRender] = useState(false)
  //定义一个控制批量删除按键的开关
  const [isSelect,setIsSelect] = useState(true)
  //定义一个保存批量删除的ids数组
  const [batchDeleteIds , setBatchDeleteIds] = useState<key[]>([])

  const getHosSetList = async () => {
    const re = await getHospitalSetListRequest({
      page: current,
      limit: pageSize,
      ...fieldsValue
    })
    // console.log('reqResult',re)
    // console.log('records',re.records)
    setTableData(re.records)
    setTotal(re.total)
    setIsLoading(false)
  }

  useEffect(() => {
    //设置初始值
    setIsLoading(true)

    getHosSetList();

  }, [current, pageSize, fieldsValue, reRender])


  const columns = [
    {
      title: '序号',
      align: 'center' as 'center',
      width: 80,
      render(_: any, __: any, index: number) {
        return index + 1
      }
    },
    {
      title: '医院名称',
      dataIndex: 'hosname',
    },
    {
      title: '医院编号',
      dataIndex: 'hoscode',
    },
    {
      title: 'api基础路径',
      dataIndex: 'apiUrl',
    },
    {
      title: '签名',
      dataIndex: 'signKey',
    },
    {
      title: '联系人姓名',
      dataIndex: 'contactsName',
    },
    {
      title: '联系人电话',
      dataIndex: 'contactsPhone',
    },
    {
      title: '操作',
      dataIndex: 'name',
      fixed: 'right' as 'right',
      render(_: any, data: getHosSetListItem) {

        const {id} = data

        const deleteHosHandle = () => {
          return async () => {
            await deleteHosRequest(id)
            await getHosSetList()
            message.success('删除数据成功！！！')
          }
        }
        return (
          <div>
            <Tooltip title='修改医院数据'>
              <Button
                type="primary"
                icon={<EditOutlined/>}
                className={style.mr}
                onClick={() => {
                  navigate(`/syt/hospital/updatehosmessage/${id}`)
                }}
              />
            </Tooltip>
            <Tooltip title='删除医院数据'>
              <Button
                type="primary"
                danger
                icon={<DeleteOutlined/>}
                onClick={deleteHosHandle()}
              />
            </Tooltip>
          </div>
        )
      }
    },


  ];


  //设置页码改变时调用的函数
  const pageChange = (current: number, pageSize: number) => {

    setCurrent(current)
    setPageSize(pageSize)

  }
  //查询数据
  const searchHosFinish = (fieldValue: fieldsValueType) => {
    setFieldsValue(fieldValue)
    message.success('查询数据成功！！！')
  }
  //设置添加医院的路由跳转
  const addOrUpdateHosHandle = () => {
    navigate('/syt/hospital/addorupdatehos')
  }
  //设置批量删除请求
  const batchDeleteHandle =async () =>{
    //执行批量删除
    await batchDeleteRequest(batchDeleteIds)
    message.success('批量删除成功!!')
    console.log('batchDeleteIds',batchDeleteIds)
    //重新渲染页面
    getHosSetList()
    //改变批量删除的按钮
    setIsSelect(true)
  }
  return (
    <div className={style.outer}>
      <Card>
        <Form
          name="basic"
          wrapperCol={{span: 24}}
          initialValues={{remember: true}}
          autoComplete="off"
          layout="inline"
          onFinish={searchHosFinish}
        >
          <Form.Item
            name="hosname"
          >
            <Input placeholder="医院名称"/>
          </Form.Item>

          <Form.Item
            name="hoscord"
          >
            <Input placeholder="医院编号"/>
          </Form.Item>

          <Form.Item wrapperCol={{span: 30}}>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined/>}>
              查询
            </Button>
          </Form.Item>
          <Form.Item wrapperCol={{span: 30}}>
            <Button
              type="default"
              htmlType="reset"
              onClick={() => {
                window.location.reload()
              }}>
              清空
            </Button>
          </Form.Item>
        </Form>

        <div className={style.mt}>
          <Button
            type='primary'
            className={style.mr}
            onClick={addOrUpdateHosHandle}
          >添加</Button>
          <Button
            type="primary"
            danger
            disabled={isSelect}
            onClick={batchDeleteHandle}
          >批量删除</Button>
        </div>

        <Table
          columns={columns}
          dataSource={tableData}
          className={style.mt}
          scroll={{x: 1200}}
          bordered
          rowKey="id"
          loading={isLoading}
          pagination={
            {
              current,
              pageSize,
              showQuickJumper: true,
              pageSizeOptions: [2, 4, 8, 12, 20],
              showSizeChanger: true,
              total,
              showTotal(total) {
                return `总数量${total}`
              },
              onChange: pageChange
            }
          }
          rowSelection={{
            onChange(ids:key[]){
              setIsSelect(!ids.length)
              //保存ids产生的数组
              setBatchDeleteIds(ids)
            }
          }}
        />
      </Card>
    </div>
  )
}